<?php

namespace App\Models;

use App\Models\Traits\ActiveUserHelper;
use App\Models\Traits\LastActivedAtHelper;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Console\Concerns\HasParameters;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasDateTimeFormatter;
    use SoftDeletes;
    use HasFactory;
    use HasRoles;
    use \Illuminate\Auth\MustVerifyEmail;
    use ActiveUserHelper;
    use LastActivedAtHelper;
    use Notifiable {
        notify as protected overwriteNotify;
    }

    public function notify($instance)
    {
        // 如果要通知的人是当前用户，就不必通知了！
        // 但是邮箱验证的的时候，需要发送。
        // 注意未能收到邮件，主要这里的逻辑。
        /*if ($this->id == Auth::id() && !request()->is('email/resend')) {
            return;
        }*/

        // 只有数据库类型通知才需提醒，直接发送 Email 或者其他的都 Pass
        if (method_exists($instance, 'toDatabase')) {
            $this->increment('notification_count');
        }

        $this->overwriteNotify($instance);
    }


    protected $fillable = [
        'name',
        'email',
        'password',
        'avatar',
        'introduction',
    ];


    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'last_actived_at' => 'datetime',
    ];

    public function topics(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Topic::class);
    }

    public function isAuthorOf($model): bool
    {
        return $this->id == $model->user_id;
    }

    public function replies(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Reply::class);
    }

    public function markAsRead()
    {
        $this->notification_count = 0;
        $this->save();
        $this->unreadNotifications->markAsRead();
    }

    public function getAvatarAttribute($value)
    {
        if (strpos($value, '//') !== false) {
            return $value;
        }

        return Storage::url($value);
    }

}
